package com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.accountservice.controller;

import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.accountservice.dto.AccountReduceBalanceDTO;
import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.accountservice.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 商品 控制器
 *
 * @author ziyucoding
 * @date 2022-11-03
 **/
@RestController
@RequestMapping("/account")
public class AccountController {

    private Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private AccountService accountService;

    @PostMapping("/reduce-balance")
    public Map<String, Object> createOrder(@RequestBody AccountReduceBalanceDTO accountReduceBalanceDTO) {
        logger.info("[reduceBalance] 收到减少余额请求, 用户:{}, 金额:{}", accountReduceBalanceDTO.getUserId(),
                accountReduceBalanceDTO.getPrice());

        boolean isSuccess = false;
        try {
            accountService.reduceBalance(accountReduceBalanceDTO.getUserId(), accountReduceBalanceDTO.getPrice());
            // 正常扣除余额，返回 true
            isSuccess = true;
        } catch (Exception e) {
            // 失败扣除余额，返回 false
            logger.error("扣除库存失败", e);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "成功");
        result.put("data", isSuccess);
        return result;
    }

}
